const {
    app,
    BrowserWindow,
    globalShortcut,
    Menu, Tray
} = require('electron');
app.commandLine.appendSwitch('allow-file-access-from-files');
const path = require('path');
const log4js = require('log4js');
log4js.configure({
    appenders: { 'ft': { type: 'dateFile', layout: {
        type: 'pattern',
        pattern: '[%d{yyyy-MM-dd hh:mm:ss}] [%p] %c - %m'
    }, filename: path.join(app.getPath('logs'), 'ft.log') } },
    categories: { default: { appenders: ['ft'], level: 'info' } }
});
const logger = log4js.getLogger('ft');

process.on('uncaughtException', (err, orign) => {
    console.error('main.js 7 : ', err, orign);
    logger.error('[main uncaughtException] ', err, orign);
});
const ipc = require('./main/ipc');
const db = require('./main/db');
const os = require('os');
console.log(app.getPath('userData'));
let win;
let tray = null;
function createWindow () {
    // 创建浏览器窗口
    win = new BrowserWindow({
        width: 1500,
        height: 800,
        frame: false,
        icon: './logo.ico',
        webPreferences: {
            nodeIntegration: true
        }
    });
    ipc._register('base', win);

    // 并且为你的应用加载index.html
    //   win.loadFile('index.html')
    // win.loadURL('http://localhost:3000')
    process.env.DEVELOPMENT ? win.loadURL('http://localhost:4000') : win.loadFile('./build/index.html');

    let icon = './logo.ico';
    if (os.platform() === 'win32' || os.platform() === 'linux') {
        if (os.platform() === 'linux') {
            icon = './logo.icns';
        }
        tray = new Tray(path.join(__dirname, icon));
        const contextMenu = Menu.buildFromTemplate([
            { label: '退出', type: 'normal', role: 'quit' }
        ]);
        // 双击打开
        tray.on('double-click', () => {
            win && win.show();
        });
        tray.setContextMenu(contextMenu);
    }
    // 打开开发者工具
    // win.webContents.openDevTools();
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// 部分 API 在 ready 事件触发后才能使用。
app.whenReady().then(createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // 在 macOS 上，除非用户用 Cmd + Q 确定地退出，
    // 否则绝大部分应用及其菜单栏会保持激活。
    logger.info('[main window-all-closed]');
    if (process.platform === 'darwin') {
        return;
    }
    db.destroyAll();
    if (process.platform !== 'darwin') {
        app.quit();
        logger.info('[main]', 'quite');
    }
});

app.on('activate', () => {
    // 在macOS上，当单击dock图标并且没有其他窗口打开时，
    // 通常在应用程序中重新创建一个窗口。
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
})
;
